// pages/lifeService/managementFee/invite.js
const app = getApp();
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "访客邀请", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent',
      goUrl:'/pages/lifeService/managementFee/menu'
    },
    showShareBtn:false,
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    showArray: [
      [],
      [],
      [],
      []
    ], //展示数据
    array: [
      [],
      [],
      [],
      []
    ], // 数据数组，分别对应三级联动的数据
    city: ['请选择房号', '', '', ''], // 默认选中的值
    curBuildId: 0, //当前楼栋Id
    //组团
    groupList: [],
    //单元
    buildingList: [],
    //楼栋
    unitList: [],
    //房号
    roomList: [],
    familyIdArr: [],
    familyId: '',
    time: '请选择上门时间',
    relation: '请选择访客关系',
    relationId: -1,
    relationList: [{
        id: '1',
        name: '朋友'
      },
      {
        id: '2',
        name: '亲戚'
      },
      {
        id: '3',
        name: '装修'
      },
      {
        id: '4',
        name: '其他'
      }
    ],
    name: '',
    phone: '',
    carNum: '',
    userId: '',
    shareTitle: '',
    shareImg: '',
    sharePath:'/pages/index/index',
  },
  //选择访客关系
  relationChange(e) {
    let that = this;
    let id = that.data.relationList[e.detail.value].id;
    that.setData({
      relationId: id,
      relation: that.data.relationList[e.detail.value].name,
    });

  },
  //访客姓名
  nameIpt(e) {
    this.setData({
      name: e.detail.value
    })
  },
  //访客电话
  phoneIpt(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  //到访车牌
  carNumIpt(e) {
    this.setData({
      carNum: e.detail.value
    })
  },
  //提交
  tj() {
    let that = this;
    let roomNum = that.data.city;
    let name = that.data.name;
    let phone = that.data.phone;
    let relation = that.data.relation;
    let time = that.data.time.value;
    let carNum = that.data.carNum;
    var data = {};
    if (roomNum[0] == "请选择房号") {
      app.showTip("请选择房号");
      return;
    }
    if (name == "") {
      app.showTip("请输入访客姓名");
      return;
    }
    if (phone == "") {
      app.showTip("请输入访客电话");
      return;
    }
    if (relation == "请选择访客关系") {
      app.showTip("请选择访客关系");
      return;
    }
    if (time == "请选择上门时间") {
      app.showTip("请选择上门时间");
      return;
    }
    data.userId = that.data.userId;
    data.visitTime = time;
    data.visitorMobile = phone;
    data.visitorName = name;
    data.inviteType = 1;
    data.relationShip = that.data.relationId;
    data.inviteAddr = roomNum.join('');
    if (carNum != "") {
      data.visitorLicensePlateNum = carNum;
    }
    wx.showLoading({
      title: '邀请生成中...'
    });

    wx.request({
      url: that.data.baseUrl + 'api/getApiData.php',
      method: 'POST',
      data: {
        'apiUrl': '/openapi/visitor/v1/invite',
        'data': JSON.stringify(data)
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          app.showTip("生成邀请成功");
          that.setData({
            showShareBtn:true,
            sharePath:'/pages/lifeService/managementFee/inviteCode?id=' + res.data.data,
          })
          // wx.navigateTo({
          //   url: '/pages/lifeService/managementFee/inviteCode?id=' + res.data.data,
          // })
        } else {
          app.showTip(res.data.msg)
        }
      },
      fail: function (res) {
        wx.hideLoading();
        app.showTip('服务器繁忙,请稍候重试');
      }
    });


  },
  onPageScroll(t) {
    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },

  bindChange: function (e) {
    const val = e.detail.value;
    console.log("val:", val)
    console.log("this.data.array:", this.data.array)
    this.setData({
      city: [
        this.data.array[0][val[0]].name,
        this.data.array[1][val[1]].name,
        this.data.array[2][val[2]].name,
        this.data.array[3][val[3]].name
      ],
      familyId: this.data.familyIdArr[val[0]]
    });
    console.log("familyId:", this.data.familyId)
  },
  bindColumnChange: function (e) {
    let that = this;
    const col = e.detail.column;
    const val = e.detail.value;
    const array = that.data.array;
    var showArray = that.data.showArray;
    var groupList = that.data.groupList;
    var buildingList = that.data.buildingList;
    var unitList = that.data.unitList;
    var roomList = that.data.roomList;
    // 根据选择的建筑更新单元和楼层数据
    var buildingListNew = [];
    var unitListNew = [];
    var roomListNew = [];
    buildingListNew[0] = buildingList[val];
    unitListNew[0] = unitList[val];
    roomListNew[0] = roomList[val];

    showArray[0] = groupList.map((item) => {
      return item.name
    })
    showArray[1] = buildingListNew.map((item) => {
      return item.name
    })
    showArray[2] = unitListNew.map((item) => {
      return item.name
    })
    showArray[3] = roomListNew.map((item) => {
      return item.name
    })

    array[0] = groupList;
    array[1] = buildingListNew;
    array[2] = unitListNew;
    array[3] = roomListNew;
    console.log("arrar:", array)

    that.setData({
      array,
      showArray
    })
  },
  //选择截止日期
  onPickerChange(e) {
    let that = this;
    that.setData({
      time: e.detail
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this;
    //后台更新楼栋单元房号信息
    //that.changeInfo(0, 3001, 0, 0);
    var data = {};
    //获取缓存中的openid"oZYOb4ktAvmrb5TsIPBHlrGEKcZg"//
    var openid = wx.getStorageSync('ly24_openid');
    var array = that.data.array;
    var showArray = that.data.showArray;
    var groupList = that.data.groupList;
    var buildingList = that.data.buildingList;
    var unitList = that.data.unitList;
    var roomList = that.data.roomList;
    var familyIdArr = that.data.familyIdArr;

    var buildingListNew = [];
    var unitListNew = [];
    var roomListNew = [];
    wx.request({
      url: that.data.baseUrl + 'api/getUserId.php',
      method: 'POST',
      data: {
        'openid': openid,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if (res.data.status == 1) {
          var userId = res.data.userId;
          var data1 = {
            "userId": userId
          }
          that.setData({
            userId: userId
          })
          wx.request({
            url: that.data.baseUrl + 'api/getApiData.php',
            method: 'POST',
            data: {
              'apiUrl': '/openapi/family/v1/queryUserFamilies',
              'data': JSON.stringify(data1)
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              if (res.data.status == 1) {
                var homeInfoList = res.data.data;
                if (homeInfoList.length == 0) {
                  app.showTip('您当前不是业主或家人身份哦');
                  setTimeout(function () {
                    wx.navigateBack({
                      delta: 1
                    });
                  }, 1500);
                  return;
                } else {

                  for (var i = 0; i < homeInfoList.length; i++) {
                    var groupObj = {};
                    var buildingObj = {};
                    var unitObj = {};
                    var roomObj = {};
                    groupObj.id = homeInfoList[i].groupId;
                    groupObj.name = homeInfoList[i].groupName;
                    buildingObj.groupId = homeInfoList[i].groupId;
                    buildingObj.id = homeInfoList[i].buildingId;
                    buildingObj.name = homeInfoList[i].buildingName;
                    unitObj.groupId = homeInfoList[i].groupId;
                    unitObj.buildingId = homeInfoList[i].buildingId;
                    unitObj.id = homeInfoList[i].unitId;
                    unitObj.name = homeInfoList[i].unitName;
                    roomObj.groupId = homeInfoList[i].groupId;
                    roomObj.buildingId = homeInfoList[i].buildingId;
                    roomObj.unitId = homeInfoList[i].unitId;
                    roomObj.id = homeInfoList[i].roomId;
                    roomObj.name = homeInfoList[i].roomName;
                    groupList.push(groupObj);
                    buildingList.push(buildingObj);
                    unitList.push(unitObj);
                    roomList.push(roomObj);
                    familyIdArr.push(homeInfoList[i].id)
                  }

                  buildingListNew[0] = buildingList[0];
                  unitListNew[0] = unitList[0];
                  roomListNew[0] = roomList[0];

                  array[0] = groupList;
                  array[1] = buildingListNew;
                  array[2] = unitListNew;
                  array[3] = roomListNew;
                  console.log("arrar:", array)
                  showArray[0] = groupList.map((item) => {
                    return item.name
                  })
                  showArray[1] = buildingListNew.map((item) => {
                    return item.name
                  })
                  showArray[2] = unitListNew.map((item) => {
                    return item.name
                  })
                  showArray[3] = roomListNew.map((item) => {
                    return item.name
                  })
                  that.setData({
                    groupList: groupList,
                    buildingList: buildingList,
                    unitList: unitList,
                    roomList: roomList,
                    array: array,
                    showArray: showArray,
                    familyIdArr: familyIdArr
                  });
                }

              }
            },
            fail: function (res) {}
          });
        }
      },
      fail: function (res) {}
    });
    let inviteId = options.id;
    if (inviteId) {
      var data = {
        id: inviteId
      }
      wx.request({
        url: that.data.baseUrl + 'api/getApiData.php',
        method: 'POST',
        data: {
          'apiUrl': '/openapi/visitor/v1/inviteInfo',
          'data': JSON.stringify(data)
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          if (res.data.status == 1) {
            wx.hideLoading();
            console.log(res.data.data)
            let inviteInfo = res.data.data;
            let inviteAddrArr = inviteInfo.inviteAddr.split('-');
            let cityArr =  that.data.city;
            cityArr[0] = inviteAddrArr[0];
            cityArr[1] = inviteAddrArr[1];
            cityArr[2] = inviteAddrArr[2];
            cityArr[3] = inviteAddrArr[3];
            let visitorName = inviteInfo.visitorName;
            let visitorMobile = inviteInfo.visitorMobile;
            let relationShipDesc = inviteInfo.relationShipDesc;
            let visitorLicensePlateNum = inviteInfo.visitorLicensePlateNum
            that.setData({
              city:cityArr,
              name:visitorName,
              phone:visitorMobile,
              relation:relationShipDesc,
              carNum:visitorLicensePlateNum
            })
            // that.setData({
            //   inviteInfo: res.data.data
            // })
          }else{
            app.showTip(res.data.msg);
          }
        },
        fail: function (res) {
          //调用最终上传数据
          wx.hideLoading();
          app.showTip('服务器繁忙,请稍候重试');
        }
      });
    }
   
    //调用分享
    that.getShareInfo();
  },
  goList() {
    wx.navigateTo({
      url: '/pages/lifeService/managementFee/inviteRecord',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: that.data.sharePath,
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})